package com.example.stars_project_android.fragment;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.example.stars_project_android.R;
import com.example.stars_project_android.adapter.MyAdapter;
import com.example.stars_project_android.entity.SpaceTime;
import com.example.stars_project_android.index.CreateRoom;
import com.example.stars_project_android.index.Search;
import com.example.stars_project_android.util.Constant;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 首页的fragment
 */
public class HomeFragment extends Fragment {
    private TabLayout mTabLayout;
    private ViewPager2 mViewPager2;
    private List<String> mData = new ArrayList<>();
    private EditText editSearch;  //搜索框
    private int code;   //返回的状态码
    private String msgCon;  //返回的信息
    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理子线程发送的消息
            String result = (String) msg.obj;
            try {
                JSONObject jsonObject = new JSONObject(result);
                code = jsonObject.getInt("code");
                msgCon = jsonObject.getString("msg");
                Log.e("状态码", code + "");
                Log.e("返回的提示信息：", msgCon);
                if (code == 200) {
                    //处理收到数据
                    if (Constant.roomList.size() != 0){
                        Constant.roomList.clear();
                    }
                    JSONObject jsonObject1 = jsonObject.getJSONObject("date");
                    JSONArray jsonArray = jsonObject1.getJSONArray("content");
                    for (int i = 0; i < jsonArray.length(); i++){
                        JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                        SpaceTime spaceTime = new SpaceTime();
                        spaceTime.setRoomId(jsonObject2.getString("roomId"));
                        spaceTime.setCreateTime(jsonObject2.getString("createTime"));
                        spaceTime.setRoomName(jsonObject2.getString("roomName"));
                        spaceTime.setUserCountMax(jsonObject2.getInt("userCountMax"));
                        spaceTime.setUserCountCurrent(jsonObject2.getInt("userCountCurrent"));
                        spaceTime.setUserPhone(jsonObject2.getString("userPhone"));
                        spaceTime.setRoomDescribe(jsonObject2.getString("roomDescribe"));
                        spaceTime.setRoomAttribute(jsonObject2.getString("roomAttribute"));
                        spaceTime.setRoomState(jsonObject2.getString("roomState"));
                        Constant.roomList.add(spaceTime);
                    }
                }
            }catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        editSearch = getActivity().findViewById(R.id.edit_search);
        //设置编辑框的不可编辑可点击
//        setCanNotEditAndClick();
        editSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editSearch.setFocusable(false);
                editSearch.setFocusableInTouchMode(false);
                //获取搜索发现的房间信息的数据
//                getConn("Search");
                Intent intent = new Intent(getActivity(), Search.class);
                startActivity(intent);
            }
        });
        //悬浮按钮点击事件
        FloatingActionButton fab = getActivity().findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), CreateRoom.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_home, container, false);
        initData();
        initView(rootView);

        //默认聊天时空被选中
        mTabLayout.getTabAt(0).select();
        //导航栏的点击事件
        //导航栏选中加粗
        mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab == null || tab.getText() == null) {
                    return;
                }
                //连接后端
                getConn(tab.getText().toString());
                String trim = tab.getText().toString().trim();
                SpannableString spStr = new SpannableString(trim);
                StyleSpan styleSpan_B = new StyleSpan(Typeface.BOLD);
                spStr.setSpan(styleSpan_B, 0, trim.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                tab.setText(spStr);

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if (tab == null || tab.getText() == null) {
                    return;
                }
                String trim = tab.getText().toString().trim();
                SpannableString spStr = new SpannableString(trim);
                StyleSpan styleSpan_B = new StyleSpan(Typeface.NORMAL);
                spStr.setSpan(styleSpan_B, 0, trim.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                tab.setText(spStr);

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        return rootView;
    }

    /**
     * 设置搜索框不可编辑只可点击
     */
    private void setCanNotEditAndClick() {
        editSearch.setFocusable(false);
        editSearch.setFocusableInTouchMode(false);
        editSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取房间信息的数据
//                getConn("Search");
                Intent intent = new Intent(getActivity(), Search.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 获取网络连接
     */
    private void getConn(String msg) {
        //向后端传递获取的信息
        //将数据封装
//        JSONObject jsonObject = new JSONObject();
//        try {
//            jsonObject.put(msg,msg);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        Log.e("json格式",jsonObject.toString());
//        MediaType type = MediaType.parse("application/json;charset=utf-8");
//        RequestBody requestBody = RequestBody.create(type,""+jsonObject.toString());

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.1.7:8080/room/findRoomByAttribute?roomAttribute="+msg)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("okhttp","请求成功");
                //处理后端的数据
                response = okHttpClient.newCall(request).execute();
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

    private void initView(View rootView) {
        mTabLayout = rootView.findViewById(R.id.tabLayout);
        mViewPager2 = rootView.findViewById(R.id.vp2);
        MyAdapter homePagerAdapter = new MyAdapter(getActivity(), mData);
        mViewPager2.setAdapter(homePagerAdapter);
        new TabLayoutMediator(mTabLayout, mViewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText(mData.get(position));
            }
        }).attach();
    }

    private void initData() {
        mData.add("聊天时空");
//        mData.add("连麦时空");
//        mData.add("学习时空");
        mData.add("音乐时空");
        mData.add("看剧时空");
    }
}
